use "$project_path/data/4_regdata/regdata", clear

log using "$project_path/output/appendix_tables/Appendix_Table_E1.smcl", replace

// Column 1 (Full sample)
rdrobust diff_m1_chix_econ runvar, all
rdrobust std_diff_m1_hdi runvar, all
rdrobust std_diff_m1_democracy_index runvar, all
rdrobust diff_m1_general_chix runvar, all

// Column 2 (High leader power)
rdrobust diff_m1_chix_econ runvar if subsample_high_power==1, all
rdrobust std_diff_m1_hdi runvar if subsample_high_power==1, all
rdrobust std_diff_m1_democracy_index runvar if subsample_high_power==1, all
rdrobust diff_m1_general_chix runvar if subsample_high_power==1, all

// Column 3 (Low leader power)
rdrobust diff_m1_chix_econ runvar if subsample_low_power==1, all
rdrobust std_diff_m1_hdi runvar if subsample_low_power==1, all
rdrobust std_diff_m1_democracy_index runvar if subsample_low_power==1, all
rdrobust diff_m1_general_chix runvar if subsample_low_power==1, all

// Column 4 (High globalization)
rdrobust diff_m1_chix_econ runvar if subsample_high_global==1, all
rdrobust std_diff_m1_hdi runvar if subsample_high_global==1, all
rdrobust std_diff_m1_democracy_index runvar if subsample_high_global==1, all
rdrobust diff_m1_general_chix runvar if subsample_high_global==1, all

// Column 5 (Low globalization)
rdrobust diff_m1_chix_econ runvar if subsample_low_global==1, all
rdrobust std_diff_m1_hdi runvar if subsample_low_global==1, all
rdrobust std_diff_m1_democracy_index runvar if subsample_low_global==1, all
rdrobust diff_m1_general_chix runvar if subsample_low_global==1, all

// Column 6 (No term limit)

rdrobust diff_m1_chix_econ runvar if subsample_no_term_limit==1, all 
rdrobust std_diff_m1_hdi runvar if subsample_no_term_limit==1, all 
rdrobust std_diff_m1_democracy_index runvar if subsample_no_term_limit==1, all 
rdrobust diff_m1_general_chix runvar if subsample_no_term_limit==1, all 

log close

/*
This programs tests the equality of two coefficients using the Z-test proposed by https://psycnet.apa.org/record/1995-27766-001
*/
capture program drop equality_test
program define equality_test, rclass
	args est1 est2 se1 se2
	local z = (`est1'-`est2')/sqrt((`se1')^2 + (`se2')^2)
	local pval=2*(1-normal(abs(`z')))
	local formatted_pval : di %6.3f `pval'
    return local formatted_pval = "`formatted_pval'"
end

*** Building .tex table
// Regressions 
#delimit ;
local outcomes  
		diff_m1_chix_econ
		std_diff_m1_hdi
		std_diff_m1_democracy_index
		diff_m1_general_chix
;
#delimit cr		

local subsample_count 6

// Initialize matrix of results and define value labels
local ncols = `subsample_count'*2
local nrows = 8
//Prepare matrix of coefficients and other statistics
mat Coefs = J(`nrows', `ncols', .)

mat list Coefs
	
local subsamples "_high_power _low_power _high_global _low_global _no_term_limit"

//inizialize indices
local row = 1
local next_row = `row' + 1

foreach v in `outcomes'{
	//Initialize indices
	local col = 1
	local pval_col = `subsample_count' + 1

	rdrobust `v' runvar, all
	
	//Store estimates and stats
	local b_`col': di %5.3f e(tau_cl)
	local se_`col': di %5.3f e(se_tau_rb)
	local p_`col': di %5.3f e(pv_rb)

	mat Coefs[`row',`col'] = `b_`col''
	mat Coefs[`next_row',`col'] = `se_`col''
	mat Coefs[`row',`pval_col'] = `p_`col''	
	
	foreach sub in `subsamples'{
		
		local ++col	
		local ++pval_col
		rdrobust `v' runvar if subsample`sub' == 1, all
		
		//Store estimates and stats
		local b_`col': di %5.3f e(tau_cl)
		local se_`col': di %5.3f e(se_tau_rb)
		local p_`col': di %5.3f e(pv_rb)
	
		mat Coefs[`row',`col'] = `b_`col''
		mat Coefs[`next_row',`col'] = `se_`col''
		mat Coefs[`row',`pval_col'] = `p_`col''	
		
	}
	
	local row = `row' + 2
	local next_row = `row' + 1
}

equality_test Coefs[7,2] Coefs[7,3] Coefs[8,2] Coefs[8,3]
local general_chix_eq_pval_power = r(formatted_pval)
equality_test Coefs[7,4] Coefs[7,5] Coefs[8,4] Coefs[8,5]
local general_chix_eq_pval_global = r(formatted_pval)

mat list Coefs

********************************************************************************
* 								EXPORT TABLE
********************************************************************************			
	// Clear the dataset, and use the matrix as dataset			

	clear
	svmat Coefs

	//	input variable names
	gen varname = ""
	gen temp = _n
	replace varname = "\textbf{Economic performance}" if temp == 1
	replace varname = "SE_1" if temp == 2
	replace varname = "\textbf{HDI}" if temp == 3
	replace varname = "SE_2" if temp == 4
	replace varname = "\textbf{Democracy}" if temp == 5
	replace varname = "SE_3" if temp == 6
	replace varname = "\textbf{General index}" if temp == 7
	replace varname = "SE_4" if temp == 8
	
	order varname, first
	drop temp
	  
	//Adjust the table before exporting
	replace varname = "" if strpos(varname, "SE_")>0
	order varname
	
	// Rename cols and labels
	forvalues n = 1/`subsample_count'{
		rename Coefs`n' Model`n'
	}
	//Cols where we store pvalues
	local n_min = `subsample_count' + 1
	local n_max = `subsample_count'*2
	local i = 1
	forvalues n = `n_min'/`n_max'{
		rename Coefs`n' P_Model`i'
		local ++i
	}
	
	label var varname ""
	label var Model1 "Baseline"
	label var Model2 "High"
	label var Model3 "Low"
	label var Model4 "High"
	label var Model5 "Low"
	label var Model6 "No"
	
		
	// Convert to string and add options
	forvalues i = 1/`subsample_count'{
		tostring Model`i', replace force format(%04.3f)
		replace Model`i'= "" if Model`i'=="."
		//Add parenthesis to SE and P-val
		replace Model`i' = "(" + Model`i' + ")" if missing(varname) & Model`i' !=""	

	}
	
	// Add stars
	local 3_star 0.01
	local 2_star 0.05
	local 1_star 0.10
	
	forvalues i = 1/`subsample_count'{
		
		replace Model`i' = Model`i' + "***" if P_Model`i' < `3_star'
		replace Model`i' = Model`i' + "**" if P_Model`i' < `2_star' & P_Model`i' > `3_star'
		replace Model`i' = Model`i' + "*" if P_Model`i' < `1_star' & P_Model`i' > `2_star'
		
		drop P_Model`i'
	}
	
	foreach var of varlist _all {
	qui replace `var' = ustrtrim(`var')	
}
	
	local title = "Heterogeneity by constraints on the executive"
	local filename = "baseline_het_global_checks_power"
	local output "$project_path/output/appendix_tables/Appendix_Table_E1.tex"
	local headerlines = " & &  \multicolumn{2}{c}{\textbf{Leader power}} & \multicolumn{2}{c}{\textbf{Globalization}} & \textbf{Term} \\  & & \multicolumn{2}{c}{\textbf{}} & \multicolumn{2}{c}{\textbf{}} & \textbf{limit}"
	local footnote = "\caption*{\footnotesize \emph{Notes}: This table reports estimated effects of electoral turnovers for different subsamples. Each estimate corresponds to a separate regression. The power enjoyed by the elected leader is an aggregate of power measures from V-Dem: power to dissolve the legislature, to appoint and dismiss ministers, and to propose and veto legislation (see Appendix \ref{subsec:regime_char} for more details). We proxy globalization with trade intensity. For these two dimensions of heterogeneity, we consider the value of the variable in the year before each election, compute the median among close elections (i.e., elections for which the running variable is under 15 percentage points in absolute value), and split the sample between elections above and below the median. In column (6), we restrict the sample to parliamentary elections and presidential elections for which there were no differentially binding term limits for the incumbent and the best ranked challenger. Using the method of \cite{clogg1995statistical}, we can marginally reject the equality of the estimates for the general index for high and low leader power (p-val. = `general_chix_eq_pval_power'), but not for high and low globalization (p-val. = `general_chix_eq_pval_global'). We obtain broadly consistent results when running a parametric regression in which we include the interaction between the treatment and the dimension of heterogeneity.  $^{*} p<0.10,^{**} p<0.05,^{***} p<0.01$.}"


	texsave using "`output'", replace title("`title'") varlabels noendash ///
							  footnote("`footnote'") ///
							  headerlines("`headerlines'" "& (1) & (2) & (3) & (4) & (5) & (6) " ) ///
							  frag nofix marker("tab:`filename'") location(H)
	